//
//  MYStatusListViewModel.swift
//  Sina
//
//  Created by 王亮龙1 on 16/5/25.
//  Copyright © 2016年 lianglong. All rights reserved.

/* 把加载数据放到了这个类里 */

import UIKit

class MYStatusListViewModel: NSObject {
    
    lazy var statusViewModelArray: [MYStatusViewModel] = [MYStatusViewModel]()

    func loadData(isPulling: Bool, finshed: (isSuccess: Bool) -> () ) {
        
        
        var since_id: Int64 = 0
        var max_id: Int64 = 0
        
        if isPulling {
            max_id = statusViewModelArray.last?.status?.id ?? 0
        } else {
            since_id = statusViewModelArray.first?.status?.id ?? 0
        }
        
        MYNetworkingTools.shareTools.loadHomeData(since_id, max_id: max_id) { (responseObject, error) in
            
            //网络错误
            if error != nil {
                
                //只发送网络请求,获取数据,不负责UI
                // SVProgressHUD.showWithStatus(APPErrorTip)
                
                finshed(isSuccess: false)
                return
            }
            
            //响应数据不是字典
            guard let dict = responseObject as? [String : AnyObject] else {
                finshed(isSuccess: false)
                
                return
            }
            
            //得到的字典key [statuses]  不是数组
            guard let array = dict["statuses"] as? [[String : AnyObject]] else {
                finshed(isSuccess: false)
                
                return
            }
            
            var tempArr = [MYStatusViewModel]()
            
            for item in array {
                //字典转模型
                let s = MYStatus(dict: item)
                
                let viewmodel = MYStatusViewModel(status: s)
                tempArr.append(viewmodel)
            }
            
            if isPulling {
                self.statusViewModelArray = self.statusViewModelArray + tempArr
            } else {
                self.statusViewModelArray = tempArr + self.statusViewModelArray
            }
            
            
            //执行成功闭包
            finshed(isSuccess: true)
        }

    }
    

    
}
